using System;
using System.Collections.Specialized;
using System.Web.Security;
using Be.Timvw.Framework.Security;

namespace Be.Timvw.Framework.Web.Security
{
    public class OneTimePasswordMembershipProvider : MembershipProvider
    {
        public const string PasswordAlgorithmKey = "passwordAlgorithm";
        public const string PasswordEpochKey = "passwordEpoch";
        public const string PasswordNumberOfDigitsKey = "passwordNumberOfDigits";
        public const string PasswordTimeStepKey = "passwordTimeStep";
        public const string ProviderTypeKey = "providerType";

        private string algorithmName;
        private DateTime epoch;
        private MembershipProvider membershipProvider;
        private int numberOfDigits;
        private int timeStep;

        public override string ApplicationName
        {
            get { return this.membershipProvider.ApplicationName; }
            set { this.membershipProvider.ApplicationName = value; }
        }

        public override bool EnablePasswordReset
        {
            get { return this.membershipProvider.EnablePasswordReset; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return this.membershipProvider.EnablePasswordRetrieval; }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return this.membershipProvider.MaxInvalidPasswordAttempts; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return this.membershipProvider.MinRequiredNonAlphanumericCharacters; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return this.membershipProvider.MinRequiredPasswordLength; }
        }

        public override int PasswordAttemptWindow
        {
            get { return this.membershipProvider.PasswordAttemptWindow; }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { return this.membershipProvider.PasswordFormat; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return this.membershipProvider.PasswordStrengthRegularExpression; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return this.membershipProvider.RequiresQuestionAndAnswer; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return this.membershipProvider.RequiresUniqueEmail; }
        }

        public override void Initialize(string name, NameValueCollection config)
        {
            this.membershipProvider = (MembershipProvider) Activator.CreateInstance(Type.GetType(config[ProviderTypeKey]));

            this.numberOfDigits = config[PasswordNumberOfDigitsKey] == null ? HmacOneTimePassword.DefaultNumberOfDigits : int.Parse(config[PasswordNumberOfDigitsKey]);
            this.algorithmName = config[PasswordAlgorithmKey] ?? HmacOneTimePassword.DefaultAlgorithmName;
            this.epoch = config[PasswordEpochKey] == null ? TimeOneTimePassword.DefaultEpoch : DateTime.Parse(config[PasswordEpochKey]);
            this.timeStep = config[PasswordTimeStepKey] == null ? TimeOneTimePassword.DefaultTimeStepSeconds : int.Parse(config[PasswordTimeStepKey]);

            config.Remove(PasswordNumberOfDigitsKey);
            config.Remove(PasswordAlgorithmKey);
            config.Remove(PasswordEpochKey);
            config.Remove(PasswordTimeStepKey);
            config.Remove(ProviderTypeKey);

            base.Initialize(name, config);
            this.membershipProvider.Initialize(name, config);
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            return this.membershipProvider.ChangePassword(username, oldPassword, newPassword);
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            return this.membershipProvider.ChangePasswordQuestionAndAnswer(username, password, newPasswordQuestion, newPasswordAnswer);
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            return this.membershipProvider.CreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status);
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            return this.membershipProvider.DeleteUser(username, deleteAllRelatedData);
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            return this.membershipProvider.FindUsersByEmail(emailToMatch, pageIndex, pageSize, out totalRecords);
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            return this.membershipProvider.FindUsersByName(usernameToMatch, pageIndex, pageSize, out totalRecords);
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            return this.membershipProvider.GetAllUsers(pageIndex, pageSize, out totalRecords);
        }

        public override int GetNumberOfUsersOnline()
        {
            return this.membershipProvider.GetNumberOfUsersOnline();
        }

        public override string GetPassword(string username, string answer)
        {
            return this.membershipProvider.GetPassword(username, answer);
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            return this.membershipProvider.GetUser(username, userIsOnline);
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            return this.membershipProvider.GetUser(providerUserKey, userIsOnline);
        }

        public override string GetUserNameByEmail(string email)
        {
            return this.membershipProvider.GetUserNameByEmail(email);
        }

        public override string ResetPassword(string username, string answer)
        {
            return this.membershipProvider.ResetPassword(username, answer);
        }

        public override bool UnlockUser(string userName)
        {
            return this.membershipProvider.UnlockUser(userName);
        }

        public override void UpdateUser(MembershipUser user)
        {
            this.membershipProvider.UpdateUser(user);
        }

        public override bool ValidateUser(string username, string password)
        {
            try
            {
                string secret = this.membershipProvider.GetUser(username, false).GetPassword();
                TimeOneTimePassword oneTimePassword = new TimeOneTimePassword(this.algorithmName, secret, this.numberOfDigits, this.epoch, this.timeStep);

                return oneTimePassword.GetPassword() == password;
            }
            catch(Exception)
            {
                return false;
            }
        }
    }
}